package com.concurrency.example.deadLock.p1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 顺序死锁
 */
public class LeftRightDeadLock2 {
    private final Object left = new Object();
    private final Object right = new Object();

    public void leftRight() throws InterruptedException{

        synchronized (left) {
            TimeUnit.SECONDS.sleep(3);
            synchronized (right) {
                System.out.println("执行任务A");
            }
        }
        Lock lock = new ReentrantLock();
        lock.tryLock();

    }

    public void rightLeft() throws InterruptedException{
        synchronized (right) {
            TimeUnit.SECONDS.sleep(3);
            synchronized (left) {
                System.out.println("执行任务B");
            }
        }
    }

    public static void main(String[] args){
        /**
         * 两个现成分别获得了锁left、right，同时等待对方持有的right、left
         * 如果这两个方法的获取锁的顺序相同就不会发生死锁
         */
        LeftRightDeadLock2 deadLock = new LeftRightDeadLock2();
        new Thread(() -> {
            try {
                deadLock.leftRight();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                deadLock.rightLeft();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
